<template>
  <div class="login-page">
    <div class="top-bar">
      <el-icon class="logo-icon">
        <img src="../assets/icon/LOGO.png" alt="Logo" />
      </el-icon>
      <div class="logo-text">红星党建平台</div>
    </div>

    <div class="main-content">
      <img class="side-image" src="../assets/bac/Login-bac.jpg" alt="Login Background" />

      <el-card class="auth-card">
        <div class="card-icon">
          <el-icon><UserFilled /></el-icon>
        </div>

        <!-- Login Form -->
        <el-form v-if="!showRegister" :model="loginForm" :rules="loginRules" ref="loginForm">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              :type="passwordVisible ? 'text' : 'password'"
              placeholder="密码"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
              <template #suffix>
                <el-icon @click="togglePasswordVisibility" style="cursor: pointer;">
                  <View v-if="!passwordVisible" />
                  <Hide v-else />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="captcha">
            <el-input v-model="loginForm.captcha" placeholder="验证码">
              <template #prefix>
                <el-icon><Tickets /></el-icon>
              </template>
            </el-input>
            <span class="captcha-code">{{ captchaCode }}</span>
            <el-button @click="generateCaptcha" class="refresh-captcha">刷新验证码</el-button>
          </el-form-item>

          <el-form-item class="form-buttons">
            <el-button type="primary" @click="login">登录</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>

          <div class="register-link">
            <span @click="toggleRegister">还没有账户？去注册 →</span>
          </div>
        </el-form>

        <!-- Register Form -->
        <el-form v-else :model="registerForm" :rules="registerRules" ref="registerForm">
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="userphone">
            <el-input v-model="registerForm.userphone" placeholder="手机号">
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="Postcard">
            <el-input v-model="registerForm.Postcard" placeholder="身份证号">
              <template #prefix>
                <el-icon><Postcard /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="register" style="width: 350px;">注册</el-button>
          </el-form-item>
          <div class="login-link">
            <span @click="toggleRegister">已有账户？去登录 ←</span>
          </div>
        </el-form>
      </el-card>
    </div>

    <div class="bottom-bar">
      © 版权信息
    </div>
    
    <!-- 确认角色错误的模态框 -->
    <el-dialog :visible.sync="showRoleErrorDialog" title="角色错误">
      <span>角色权限错误，请联系管理员。</span>
      <span>是否跳转到百度?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRoleErrorDialog = false">取消</el-button>
        <el-button type="primary" @click="redirectToBaidu">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { User, Lock, UserFilled, Phone, Postcard, Tickets } from '@element-plus/icons-vue';
import { View, Hide } from '@element-plus/icons-vue';
import { useTokenStore } from '@/stores/token';
import { userLoginService, userRegisterService } from '@/api/user'; // 导入 API 服务
import { ElMessage } from 'element-plus'; // 导入 Element Plus 的消息组件

export default {
  components: {
    User,
    Lock,
    UserFilled,
    Phone,
    Postcard,
    View,
    Hide,
    Tickets
  },
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        userphone: '',
        Postcard: ''
      },
      showRegister: false,
      passwordVisible: false,
      captchaCode: '',
      showRoleErrorDialog: false,
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 16, message: '用户名长度在5到16位之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 16, message: '密码长度在5到16位之间', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value !== this.captchaCode) {
                callback(new Error('验证码错误'));
              } else {
                callback();
              }
            }
          ]
        ]
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 16, message: '用户名长度在5到16位之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 16, message: '密码长度在5到16位之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value !== this.registerForm.password) {
                callback(new Error('两次输入的密码不一致!'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        userphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { len: 11, message: '手机号长度为11位', trigger: 'blur' },
        ],
        Postcard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { len: 18, message: '身份证号长度为18位', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.generateCaptcha();
  },
  setup() {
    const tokenStore = useTokenStore();
    return { tokenStore };
  },
  methods: {
    togglePasswordVisibility() {
      this.passwordVisible = !this.passwordVisible;
    },
    async login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          const formModel = {
            username: this.loginForm.username,
            password: this.loginForm.password,
            captcha: this.loginForm.captcha
          };
          const tokenStore = useTokenStore();
          try {
            const result = await userLoginService(formModel);
            if (result.data.role !== 'USER') { // 判断角色
              this.showRoleErrorDialog = true; // 显示角色错误对话框
              return;
            }
            ElMessage.success(result.msg ? result.msg : '登录成功');
            tokenStore.setToken(result.data.token);
            this.$router.push('/user');
          } catch (error) {
            ElMessage.error('登录失败，请检查输入');
          }
        }
      });
    },
    async register() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await userRegisterService({
              username: this.registerForm.username,
              password: this.registerForm.password,
              userphone: this.registerForm.userphone,
              Postcard: this.registerForm.Postcard
            });
            const { success, message } = response.data;

            if (success) {
              ElMessage.success('注册成功，转到登录界面');
              this.toggleRegister();
              this.resetForm();
            } else {
              ElMessage.error(`注册失败: ${message}`);
            }
          } catch (error) {
            console.error(error);
            ElMessage.error('注册请求失败');
          }
        }
      });
    },
    toggleRegister() {
      this.showRegister = !this.showRegister;
    },
    generateCaptcha() {
      this.captchaCode = Math.random().toString(36).substring(2, 6).toUpperCase();
    },
    resetForm() {
      if (this.showRegister && this.$refs.registerForm) {
        this.$refs.registerForm.resetFields();
      } else if (!this.showRegister && this.$refs.loginForm) {
        this.$refs.loginForm.resetFields();
        this.generateCaptcha(); 
      }
    },
    redirectToBaidu() {
      window.location.href = 'http://www.baidu.com'; // 跳转到百度
    }
  }
};
</script>

<style lang="scss" scoped src="../styles/LoginPage.scss">
</style>
